<?php
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/wxpay/jsapi/WxPay.JsApiPay.php';
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/wxpay/jsapi/log.php';

class Pay extends Base_Controller
{
	private $user_id;
    public function __construct()
    {
        parent::__construct();

        $this->load->model('transaction_model');
        $this->load->model('track_model');
        $this->load->model('article_model');
        $this->load->model('ziying_model');
        $this->load->model('userv2info_model');
        $this->load->model('userv2_model');
        $this->load->database();
        /*if(!isset($_SESSION)){
        	session_start();
        }
        if(!isset($_SESSION['is_login'])||$_SESSION['is_login'] != 1) $this->error('未登录');
        
		$this->user_id = $_SESSION['uid'];*/

    }
    public function getbookinginfo()
    {
    	$data= $_GET;

    	if(empty($data['goodsId']) || empty($data['type']))
    	{
    		$this->error('参数不全');
    	}
    	$data['type']=strtoupper($data['type']);
    	//获取汇率
    	$data['rate']=$this->transaction_model->exchange_rate();
    	$data['rate']=$data['rate']['bankConversionPri']/100;
    	
    	switch ($data['type'])
    	{//根据预定类型计算订单的价格
    		case 'TRACK':
    			$model = 'track_model';
    			$good = $this->$model->getbyid($data['goodsId']);
    			$priceBasic = ($good['priceFood'] + $good['priceTraffic'] + $good['priceTicket'] + $good['priceOther'])*1.1/100;
    			$priceService = $good['priceService']*1.1/100;
    			$daynum=$good['days'];
    			
    			$days=$good['freetimeDays'];
    			$pDays=array();
    			if(!empty($days)){
    				$days=explode(',',$days);
    				foreach( $days as $d){
    					if(!empty($d)){
    						$d=trim($d);
    						$pDays[$d]['date']=$d;
    						$pDays[$d]['priceBasic']=$priceBasic;
    						$pDays[$d]['priceService']=$priceService;
    					}
    				}
    				//去掉今天以前的日期的价格
    				$today=strtotime(date("Y-m-d"));
    				foreach ($pDays as $d=>$p){
    					$dtime=strtotime($d);
    					if($dtime<$today)
    						unset($pDays[$d]);
    				}
    			}  			
    			break;
    		case 'ACTIVITY':
    			$model = 'article_model';
    			$good = $this->$model->getbyid($data['goodsId']);
    			$priceBasic = 0;
    			$priceService =  $good['priceService']*1.1/100 ;
    			$daynum=1;
    			
    			$days=$good['freeTimeDays'];
    			$pDays=array();
    			if(!empty($days)){
    				$days=explode(',',$days);
    				foreach( $days as $d){
    					if(!empty($d)){
    						$d=trim($d);
    						$pDays[$d]['date']=$d;
    						$pDays[$d]['priceBasic']=$priceBasic;
    						$pDays[$d]['priceService']=$priceService;
    					}
    				}
    				//去掉今天以前的日期的价格
    				$today=strtotime(date("Y-m-d"));
    				foreach ($pDays as $d=>$p){
    					$dtime=strtotime($d);
    					if($dtime<$today)
    						unset($pDays[$d]);
    				}
    			}
    			break;
    		case 'ZIYING':
    			$model = 'ziying_model';
    			$good = $this->$model->getbyid($data['goodsId']);
    			$pdetail =  $good['priceDetail'];
    			$daynum=$good['days'];
    	
    			$pDays=array();
    			if(!empty($pdetail)){
    				$pdetail=explode(',',$pdetail);
    				foreach( $pdetail as $v){
    					if(!empty($v)){
    						$p=explode(':',$v);
    						//日期
    						$p[0]=trim($p[0]);
    						//该日期的项目价格
    						$p[1]=trim($p[1]);
    						$pDays[$p[0]]['date']=$p[0];
    						$pDays[$p[0]]['pricebasic']=0;
    						$pDays[$p[0]]['priceService']=$p[1];
    					}
    				}
    				//去掉今天以前的日期的价格
    				$today=strtotime(date("Y-m-d"));
    				foreach ($pDays as $d=>$p){
    					$dtime=strtotime($d);
    					if($dtime<$today)
    						unset($pDays[$d]);
    				}
    			}
    			break;
    		default:
    			$this->error('类型错误');
    	}
    	//用户信息
    	if(!isset($_SESSION)){
    		session_start();
    	}
    	if($_SESSION['is_login'] == 1) $this->user_id = $_SESSION['uid'];
    	
    	if(isset($this->user_id)){
    		$user=$this->userv2info_model->getUserV2Info(array('uvu.uid'=>$this->user_id));
    		$tourist=array('touristXing'=>$user['userFamily'],'touristMing'=>$user['userName'],
    			'touristAreaCode'=>$user['telCode'],'touristTelNum'=>$user['telNum']);
    	}else{
    		$tourist= array('touristXing'=>'','touristMing'=>'', 'touristAreaCode'=>'','touristTelNum'=>'');
    	}
 	
    	$guider=$this->userv2info_model->getUserV2Info(array('uvu.uid' => $good['uid']));
    	$gret=array('guiderIcon'=>$guider['userIcon'],'guiderName'=>$guider['userFamily'].$guider['userName'],
    			'goodsId'=>$data['goodsId'],'name'=>$good['name'], 'type'=>$data['type'], 
    			'days' => $daynum, 'rate'=>$data['rate'], 'content' => array_values($pDays));
    	
    	$ret=array_merge($gret,$tourist);
    	$this->success($ret);
    	
    }

    public function addorder()
	{
		//下订单时判断是否登陆
		if(!isset($_SESSION)){
			session_start();
		}
		if(!isset($_SESSION['is_login'])||$_SESSION['is_login'] != 1) $this->error('未登录');

		$this->user_id = $_SESSION['uid'];
		
		$data= $_POST;
        if(empty($data['goodsId']) || empty($data['type']))
        {
        	$this->error('系统参数不全');
        }
        if(empty($data['price']) || empty($data['startDay'])  || empty($data['stopDay']))
        {
        	$this->error('请选择出行日期');
        }
        if(empty($data['persons']))
        {
        	$this->error('请选择出行人数');
        }
        if(empty($data['touristXing'])){
        	$this->error('请填写姓氏');
        }
        if(empty($data['touristMing'])){
        	$this->error('请填写名字');
        }
        if(empty($data['touristAreaCode'])){
        	$this->error('请选择区号');
        }
        if(empty($data['touristTelNum'])){
        	$this->error('请填写电话');
        }
        //产品信息
        $data['type']=strtoupper($data['type']);
         switch ($data['type'])
         {
             case 'TRACK':
                 $model = 'track_model';
                 $good = $this->$model->getbyid($data['goodsId']);
                 break;
             case 'ACTIVITY':
                 $model = 'article_model';
                 $good = $this->$model->getbyid($data['goodsId']);
                 break;
             case 'ZIYING':
                 $model = 'ziying_model';
                 $good = $this->$model->getbyid($data['goodsId']);
                 break;
             default:
                 $this->error('产品类型错误，请重试');
         }
        
        //玩伴无法对自己的产品下单
        if($this->user_id == $good['uid'])
        	$this->error('不能对自己的产品下单');
        
        //订单信息
        $orderData = array(
            'status'  => 0,
            'created' => time(),
            'changed' => time(),
        );
        $orderData['addrUserName']=trim($data['touristXing']).trim($data['touristMing']);
        $orderData['addrTelNumber']='+'.trim(ltrim($data['touristAreaCode'],'+')).trim($data['touristTelNum']);        
        $orderData['title']       =$good['name'];
        $orderData['uid']         = $this->user_id;
        $orderData['shopId']      = $good['uid'];
        $orderData['countsGoods'] = 1;
        $orderData['countsQuantity'] = $data['persons'];
        $orderData['startDay']    = $data['startDay'];
        $orderData['stopDay']     = $data['stopDay'];
        $orderData['goodsId']     = $data['goodsId'];
        $orderData['goodsType']   = $data['type'];
        $orderData['persons']     = $data['persons'];

        // 金额信息
        $orderData['moneyCoin']    = 0;
        $orderData['moneyTicket']  = 0;
        $orderData['moneyDeliver'] = 0;
        $orderData['moneyGoods']   = $data['price']*100;
        $orderData['moneyTotal']   = $data['price']*100;
        $orderData['commentsUser'] = '';
        $orderData['orderType']    = 'NORMAL';
        $orderData['tuanId']       = 0;
        $r = $this->transaction_model->addOrder($orderData);

        if($r)
        {
            $this->success(array('transId'=>$r));
        }else{
            $this->error('生成订单失败');
        }

    }

    public function alipay()
    {

        if (empty($_GET['transId']))
        {
            $this->error('参数不全');
        }
        $data = $this->transaction_model->detail($_GET['transId']);
        $parameter = array(
            "out_trade_no" =>$data['out_trade_no'],
            "total_fee"    => $data['total_fee'] / 100,   // 元
            "body"         => $data['body'],
            "notify_url"   => 'http://api.wayatrip.com/pay/alicallback',
			"return_url"   => 'http://api.wayatrip.com/',
            "show_url"     => '',
            "product"      =>$data['body'],
        );
        $this->load->library('ali/Alipay');
        $this->alipay->zhifu($parameter);
    }

    public function alicallback()
    {
        $this->load->library('ali/Alipay');
        $re =  $this->alipay->get_notify();
        //var_dump($re);echo '<br><br>';        
        if ($re === false)
        {
            return FALSE;
        }

        $orderNo       =  $re['out_trade_no'];
//        $orderNo  = '201605112155000155';
        $r['transactionId'] = empty($re['transaction_id'])?null:$re['transaction_id'];
        $r['merchantId']    = NULL;
        $r['resultCode']    = 'SUCC';//$data['trade_status'];
        $r['returnCode']    = 'SUCC';//$data['trade_status'];
        $trans = $this->transaction_model->detailBy($orderNo);
        //var_dump($trans);echo '<br><br>';
        if ($trans)
        {
            $r['platform'] = 'ALIPAY';
            $this->transaction_model->notify_paid ($trans['id'], $r);
            return true;
        }
        else
        {
            return false;
        }
    }

    public function weixinpay()
    {
    	$data = $this->transaction_model->detail($_GET['transId']);
    	//初始化日志
    	$logHandler= new CLogFileHandler("/home/ali0t4/source/waya/webroot/waya_api/libraries/wxpay/logs/".date('Y-m-d').'.log');
    	$log = Log::Init($logHandler, 15);
    	
    	//获取用户openid
    	$tools = new JsApiPay();
    	
    	if(!isset($_SESSION)) session_start();
    	$openid = $_SESSION['openid'];
    	if(!isset($openid)){
    		$this->error('未登录');
    	}
    	 
    	//统一下单
    	$input = new WxPayUnifiedOrder();
    	$input->SetBody($data['body']);
    	//$input->SetAttach("test");
    	$input->SetOut_trade_no($data['out_trade_no']);
    	$input->SetTotal_fee($data['total_fee']);
    	//$input->SetTime_start(date("YmdHis"));
    	//$input->SetTime_expire(date("YmdHis", time() + 600));
    	//$input->SetGoods_tag("test");
    	$input->SetNotify_url("http://api.wayatrip.com/wxcallback");
    	//扫码支付
    	$input->SetTrade_type("NATIVE");
    	$input->SetOpenid($openid);
    	$input->SetProduct_id($data['transactionId']);
    	
    	$order = WxPayApi::unifiedOrder($input);
    	//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
    	//printf_info($order);
    	//$jsApiParameters = $tools->GetJsApiParameters($order);
    	//$this->success($order);
    	//生成二维码图片
    	$qrimg=$tools->GetQrImg($order['code_url']);
    	$this->success($qrimg);
    	 
    	//获取共享收货地址js函数参数
    	//$editAddress = $tools->GetEditAddressParameters();
    	 
    	//在支持成功回调通知中处理成功之后的事宜，见 notify.php    		
    	
    }
    
    public function wxcallback()
    {
    	
    }
    
    public function createQrimg()
    {
    	$url=empty($_GET['url'])||!isset($_GET['url']) ? '' : $_GET['url'];
    	if(!empty($url)){
    		$tools = new JsApiPay();
    		$qrimg=$tools->GetQrImg($url);
    		echo $qrimg;exit;
    	}else{
    		$this->error("参数错误");
    	}
    }

}
